package com.mac.sys.urtils;





import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ToStringUtil
{
    public static String toString(Object entity, String... fieldName)
    {
        Class cls = entity.getClass();
        StringBuffer buffer = new StringBuffer(cls.getSimpleName() + ": ");

        try
        {
            //不获取私有方法
            Method[] methods = cls.getMethods();
            if(null != fieldName && fieldName.length != 0)
            {
                for(Method method: methods)
                {
                    String mn = method.getName();
                    for(String fn: fieldName)
                    {
                        if(mn.equalsIgnoreCase("get" + fn))
                        {
                            String value = method.invoke(entity).toString();
                            buffer.append(mn + "=" + value + " &");
                        }
                    }
                }
            }
            else
            {
                //得到所有field
                Field[] fields = cls.getDeclaredFields();
                for(Method method: methods)
                {
                    String mn = method.getName();
                    for(Field field: fields)
                    {
                        String name = field.getName().toString();
                        if(mn.equalsIgnoreCase("get" + name))
                        {
                            Object valueObj = method.invoke(entity);

                            buffer.append(name + "=" + valueObj + " &");
                        }
                    }
                }
            }

        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

        return buffer.substring(0, buffer.length()-1).toString();
    }

}